package io.github.jsp.util.monitoring;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

@Component
public class NetworkUtil {
    
    private static final Logger logger = LoggerFactory.getLogger(NetworkUtil.class);
    
    public boolean isPortOpen(String host, int port, int timeoutMs) {
        try (Socket socket = new Socket()) {
            socket.connect(new InetSocketAddress(host, port), timeoutMs);
            return true;
        } catch (IOException e) {
            logger.debug("端口检查失败 {}:{} - {}", host, port, e.getMessage());
            return false;
        }
    }
    
    public CompletableFuture<Boolean> isPortOpenAsync(String host, int port, int timeoutMs) {
        return CompletableFuture.supplyAsync(() -> {
            return isPortOpen(host, port, timeoutMs);
        });
    }
    
    public boolean ping(String host, int timeoutMs) {
        try {
            InetAddress address = InetAddress.getByName(host);
            return address.isReachable(timeoutMs);
        } catch (IOException e) {
            logger.debug("Ping检查失败 {} - {}", host, e.getMessage());
            return false;
        }
    }
    
    public CompletableFuture<Boolean> pingAsync(String host, int timeoutMs) {
        return CompletableFuture.supplyAsync(() -> {
            return ping(host, timeoutMs);
        });
    }
    
    public long measureConnectTime(String host, int port, int timeoutMs) {
        long startTime = System.currentTimeMillis();
        try (Socket socket = new Socket()) {
            socket.connect(new InetSocketAddress(host, port), timeoutMs);
            return System.currentTimeMillis() - startTime;
        } catch (IOException e) {
            return -1; // 连接失败
        }
    }
    
    public CompletableFuture<Long> measureConnectTimeAsync(String host, int port, int timeoutMs) {
        return CompletableFuture.supplyAsync(() -> {
            return measureConnectTime(host, port, timeoutMs);
        });
    }
    
    public boolean isHostReachable(String host) {
        try {
            InetAddress address = InetAddress.getByName(host);
            return true;
        } catch (UnknownHostException e) {
            logger.debug("主机名解析失败: {} - {}", host, e.getMessage());
            return false;
        }
    }
}